<template>
    <el-dialog
        :visible="true"
        width="50%"
        :fullscreen="fullScreen"
        :append-to-body="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleClose">
        <span slot="title" class="el-dialog__title">
            Excel导入
            <i class="el-icon-full-screen iconClass" v-if="!fullScreen" @click="()=>{fullScreen = true}"></i>
            <i class="el-icon-aim iconClass" v-else @click="()=>{fullScreen = false}"></i>
        </span>
        <div class="dialogBody">
            <el-steps :active="active" align-center>
                <el-step title="选择Excel"></el-step>
                <el-step title="预览数据"></el-step>
                <el-step title="配置表单"></el-step>
            </el-steps>
            <div v-if="active === 1" v-loading="uploadLoading">
                <div style="margin-top: 20px;">
                    <div style="font-weight:600;margin: 0 20px">· 上传的EXCEL文件需符合以下规范:</div><br>
                    <div class="spanClass">· 不能存在合并的单元格</div><br>
                    <div class="spanClass">· 文件大小不超过2MB</div><br>
                    <div class="spanClass">· 仅支持（*.xls和*.xlsx）文件</div><br>
                    <div class="spanClass">· 文件中数据不能超过1000行、200列</div><br>
                    <div class="spanClass">· 请确保您需要导入的Sheet1表头中不包含空的单元格，否则该Sheet页数据将出现问题</div><br>
                </div>
                <div>
                    <el-upload
                        class="upload-demo"
                        drag
                        accept=".xls, .xlsx"
                        :before-upload="beforeUpload"
                        :on-success="uploadSuccess"
                        :file-list="fileList"
                        :limit="1"
                        :headers="{ 'Authorization': 'Bearer ' + localStorageTemp, 'tenant-id': tenantId }"
                        :show-file-list="false"
                        :action="loadAction">
                        <el-button icon="el-icon-upload">选择或拖拽上传文件，2MB以内</el-button>
                    </el-upload>
                </div>
            </div>
            <div v-else-if="active === 2">
                <div class="middleBody">
                    <div class="secondStepClass">
                        工作表&nbsp;<el-select v-model="sheetValue" placeholder="请选择sheet" @change="sheetChange">
                                <el-option
                                v-for="item in options"
                                :key="item"
                                :label="item"
                                :value="item">
                                </el-option>
                            </el-select>
                        &nbsp;点击任意一行可将其设置为标题行，标题行之前的数据不导入
                    </div>
                    <div class="tableBody">
                        <table style="width:100%;overflow: auto">
                            <tr :class="selectIndex === index ? 'selectRowColor' : 'noRowColor'" @click="clickRow(item, index)" v-for="(item, index) in curSheetList" :key="index">
                                <div v-if="selectIndex === index">
                                    <span class="rectangle">
                                        <div class="titleClass">标题行</div>
                                    </span>
                                    <span class="trangle"></span>
                                </div>
                                <td v-else>{{index + 1}}</td>
                                <td v-for="(cur, idx) in item.rowvalue" :key="idx" class="textLongCss" :title="cur">{{cur}}</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="previous('2')" size="small">上一步</el-button>
                    <el-button @click="nextStep" size="small">下一步</el-button>
                </span>
            </div>
            <div v-else>
                <div class="middleBody">
                    <div class="firstTableBody">
                        <table style="width:100%;overflow: auto">
                            <tr>
                                <td>字段标题</td>
                                <td v-for="(item, index) in columnLength" :key="index">
                                    <el-input type="text" v-model="firstRowList[index]" placeholder="请输入标题"/>
                                </td>
                            </tr>
                            <tr>
                                <td>字段类型</td>
                                <td v-for="(item, index) in columnLength" :key="index">
                                    <el-select placeholder="请选择" v-model="secondRowList[index]">
                                        <el-option
                                        v-for="item in paramsTypeOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                        </el-option>
                                    </el-select>
                                </td>
                            </tr>
                            <tr>
                                <td>是否必填</td>
                                <td v-for="(item, index) in columnLength" :key="index">
                                    <el-select placeholder="请选择" v-model="thirdRowList[index]">
                                        <el-option
                                        v-for="item in requiredOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                        </el-option>
                                    </el-select>
                                </td>
                            </tr>
                            <tr class='noRowColor' v-for="(item, index) in thirdshowData" :key="index">
                                <td>{{index+1}}</td>
                                <td v-for="(cur, idx) in item" :key="idx" class="textLongCss" :title="cur">{{cur}}</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="previous('3')" size="small">上一步</el-button>
                    <el-button @click="importData" size="small" type="primary">导入</el-button>
                </span>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import {inputComponents, selectComponents} from '../../../../components/generator/config.js'
import {deepClone} from '../../../../utils/index.js'
export default {
    name: 'ExcelImportDialog',
    data () {
        return {
            inputComponents: inputComponents,
            selectComponents: selectComponents,
            active: 1,
            fullScreen: false,
            fileList: [],
            options: [],
            sheetValue: '',
            tableData: [],
            sheetMap: new Map(),
            selectIndex: 0,
            requiredOption: [{
                value: 1,
                label: '是'
            },{
                value: 0,
                label: '否'
            }],
            paramsTypeOption: [{
                value: 'none',
                label: "不导入"
            },{
                value: 'input&el-input',
                label: "单行文本"
            },{
                value: 'textarea&el-input',
                label: "多行文本"
            },{
                value: 'radio&my-radio-group',
                label: "单选"
            },{
                value: 'checkbox&my-checkbox-group',
                label: "多选框组"
            },{
                value: 'select&my-select',
                label: "下拉框"
            },{
                value: 'number&el-number',
                label: "数字"
            },{
                value: 'date&el-date-picker',
                label: "日期时间"
            }],
            paramsValue: 'none',
            typeValue: 1,
            curSheetList: [],
            columnLength: 0,
            localStorageTemp: '',
            tenantId: '',
            loadAction: '',
            api: '',
            uploadLoading: false, // 遮罩层
            firstRowList: [], // 首行标题
            secondRowList: [], // 第二行类型
            thirdRowList: [], // 第三行必填
            thirdshowData: [] // 展示数据
        }
    },
    props: [],
    created () {
        this.api = process.env.VUE_APP_BASE_API;
        this.loadAction = `${this.api}/admin-api/form/project/excelinput`;
        this.localStorageTemp = window.localStorage.getItem('ACCESS_TOKEN');
        this.tenantId = window.localStorage.getItem('TENANT_ID')
    },
    methods: {
        // sheet页切换
        sheetChange (sheet) {
            this.curSheetList = [...this.sheetMap.get(sheet)]
            this.firstRowList = this.curSheetList[this.selectIndex]?.rowvalue
        },
        // 第二步单击某一行
        clickRow (row, idx) {
            this.selectIndex = idx
            this.firstRowList = [...row.rowvalue]
        },
        // 上传前钩子判断
        beforeUpload (file) {
            const size = file.size / 1024 / 1024
            if (size > 2) {
                this.$message.warning('文件最大不超过2M')
                return false
            }
            const nameLst = file.name.split('.')
            const type = nameLst[nameLst.length - 1]
            if (!['xls', 'xlsx'].includes(type)) {
                this.$message.warning('文件只支持xls,xlsx格式')
                return false
            }
            this.uploadLoading = true
        },
        // 上传成功钩子事件
        uploadSuccess (response, file, fileList) {
            if (response.code === 0) {
                response.data.forEach((item, index) => {
                    if (index === 0) {
                        if(item.rowList.length === 0) {
                            this.firstRowList = [] 
                        }else{
                            this.firstRowList = [...item.rowList[0]?.rowvalue]
                        }
                    }
                    this.sheetMap.set(item.sheetName, item.rowList)
                    this.options.push(item.sheetName)
                })
                this.sheetValue = response.data[0].sheetName
                this.curSheetList = response.data[0].rowList
                this.uploadLoading = false
                this.active = 2
            }else{
                this.fileList = []
                this.$message.error(response.msg)
                this.uploadLoading = false
            }
        },
        // 上一步
        previous (flag) {
            if (flag === '2') {
                this.active = 1
                this.sheetValue = ''
                this.curSheetList = []
                this.options = []
            } else {
                this.active = 2
            }
        },
        // 下一步
        nextStep (){
            if(this.curSheetList.length === 0){
                this.$message.warning('没有数据，请重新选择')
            }else{
                this.thirdshowData = []
                const copyList = [...this.curSheetList]
                const temp = copyList.splice(this.selectIndex + 1)
                temp.forEach(row => {
                    this.thirdshowData.push(row.rowvalue)
                })
                this.firstRowList.forEach(item => {
                    this.secondRowList.push('input&el-input') // 默认单行文本
                    this.thirdRowList.push(1) // 默认必填
                })
                this.columnLength = this.firstRowList.length
                this.active = 3
            }
        },
        // 导入
        importData () {
            for (let a = 0; a < this.firstRowList.length; a++) {
                const item = this.firstRowList[a];
                if (!item.trim()) {
                    return this.$message.warning('第'+ (a + 1) +'列字段标题为空，请重新填写')
                }
            }
            const dragList = []
            // 将所有组件整合
            const copyInputCompList = deepClone(this.inputComponents)
            const copySelectCompList = deepClone(this.selectComponents)
            const concatList = copyInputCompList.concat(copySelectCompList)
            // 根据第二行字段类型在所有组件中查找并修改对应属性
            this.secondRowList.forEach((type, index) => {
                concatList.forEach(comp => {
                    const tagIcon = comp.__config__.tagIcon
                    const tag = comp.__config__.tag
                    const typeList = type.split('&')
                    // 过滤掉不导入的字段
                    if (type !== 'none' && typeList[0] === tagIcon && typeList[1] === tag) {
                        // 日期组件 使用日期时间格式
                        if (typeList[0] === 'date') {
                            comp.type = 'datetime'
                        }
                        // 是否必填赋值
                        if (this.thirdRowList[index] === 1) {
                            comp.__config__.required = true
                        } else {
                            comp.__config__.required = false
                        }
                        // 将多选框组，单选，下拉框列的数据作为option选项值
                        if (typeList[0] === 'checkbox' || typeList[0] === 'select' || typeList[0] === 'radio') {
                            const options = []
                            const noRepeatOptions = []
                            this.curSheetList.forEach((row, idx) => {
                                // 首行标题不作为选项值(20是控制选项个数最多20个)
                                if (idx !== this.selectIndex && idx <= 20) {
                                    options.push({label: row.rowvalue[index], value: idx})
                                }
                            })
                            // 去重
                            comp.options = this.deduplication(options)
                        }
                        // 字段标题作为组件标签
                        comp.__config__.label = this.firstRowList[index]
                        const newCopyComp = deepClone(comp)
                        dragList.push(newCopyComp)
                    }
                })
            })
            this.$emit('closeExcelDialog', dragList)
        },
        // 去重option
        deduplication (options) {
            let obj = {}
            options = options.reduce((item, next) => {
                obj[next.label] ? '' : obj[next.label] = true && item.push(next);
                return item
            }, [])
            return options
        },
        // 关闭弹框
        handleClose () {
            this.$emit('closeExcelDialog', false)
        },
    }
}
</script>
<style lang="less" scoped>
.dialogBody{
    padding-top: 10px;
}
/deep/.el-dialog__title{
    width: 100%;
}
.textLongCss{
    max-width:150px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}
.rectangle{
    display: inline-block;
    margin-left: 15px;
    line-height: 30px;
    height: 20px;
    font-size:14px;
    background-color: #409EFF;
}
.titleClass{
    line-height: 20px;
    padding-left: 5px;
    color: white;
}
.trangle {
    display: inline-block;
    width: 0px;
    height: 0px;
    border: 10px solid #000;
    vertical-align: text-top;
    border-top-color: transparent;
    border-bottom-color: transparent;
    border-left-color: #409EFF;
    border-right-color: transparent;
}
.rowColor{
    background-color:#409EFF;
}
.selectRowColor{
    background-color: lightgrey;
}
.noRowColor{
    background-color: white;
}
.dialog-footer{
    float: right;
    margin-right: 20px;
}
table{
    width:350px;
    margin:0 auto;
    background-color:#eee;
}
table tr{
    font-size:14px;
    font-weight:normal;
    text-align:center;
    line-height:40px;
    white-space:nowrap;
    padding: 2px 10px;
    background-color:white;
    min-width:85px
}
table td{
    font-size:14px;
    font-weight:normal;
    text-align:center;
    white-space:nowrap;
    padding: 2px 10px;
    min-width: 150px;
}
.middleBody{
    padding: 20px;
    height: 420px;
}
.tableBody{
    height: 340px;
    overflow: auto;
    margin: 10px 0px;
    cursor: pointer;
}
.firstTableBody{
    height: 360px;
    overflow: auto;
    margin: 10px 0px;
    cursor: pointer;
}
/deep/.secondStepClass .el-select {
    width: 15%;
}
/deep/.el-input--medium .el-input__inner {
    height: 28px;
    line-height: 28px;
}
/deep/.el-input--medium .el-input__icon {
    height: 28px;
    line-height: 28px;
}
/deep/.el-upload-dragger .el-icon-upload {
    font-size: 15px;
    margin: 0px;
    line-height: 40px;
}
/deep/.el-button--medium {
    padding: 0px 20px;
    margin-top: 85px;
}
.spanClass{
    margin: 0px 20px;
    font-size: 12px;
}
.iconClass{
    float:right;
    margin-right: 35px;
    line-height: 1.5;
}
/deep/.el-upload-dragger{
    width: 100% !important;
    height: 220px;
}
/deep/.el-upload {
    width: 100%;
}
/deep/.el-dialog__body{
    height: 550px;
    padding: 0px 20px;
}
::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 5px;
}
::-webkit-scrollbar-thumb {
  background-color: skyblue;
  background-image: -webkit-linear-gradient(
    45deg,
    rgba(255, 255, 255, 0.2) 25%,
    transparent 25%,
    transparent 50%,
    rgba(255, 255, 255, 0.2) 50%,
    rgba(255, 255, 255, 0.2) 75%,
    transparent 75%,
    transparent
  );
  /*滚动条里面小方块*/
  border-radius: 10px;
}
::-webkit-scrollbar-track {
  background: #ededed;
  border-radius: 10px;
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
}
</style>